package com.module.product.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.exception.ProcessException;
import base.util.JsonMsg;
import base.util.Page;
import base.util.Tools;

import com.module.product.common.ProductConstant;
import com.module.product.vo.AttrItem;
import com.module.product.vo.AttrValue;
import com.module.product.vo.EntProduct;
import com.module.product.vo.EntProductSyn;
import com.module.product.vo.Product;
import com.module.product.vo.ProductTemporary;
/**
*
* 商品dao类
*
* @author  王勇云
* @version  [V1.0, Jul 22, 2011]
* @see  [相关类/方法]
* @since  [二代服务平台/商品]
*/
public class EntProductDao extends GenericHibernateDao<EntProduct,String>{
	private static  EntProductDao dao;
	private EntProductSynDao entProductSynDao = EntProductSynDao.getInstance();
	private ProductTemporaryDao productTemporaryDao = ProductTemporaryDao.getInstance();
	private EntProductDao(){}
	
	public synchronized static EntProductDao getInstance(){
		if(dao==null){
			dao = new EntProductDao();
		}
		return dao;
	}
	   /**
     * <逻辑删除>
     * <功能详细描述>
     * @param attrGroup
     * @return
     * @see [类、类#方法、类#成员]
     */
    public JsonMsg deleteObjs(Session session,EntProduct obj){
    	JsonMsg jsonMsg = new JsonMsg(true);
        List<ProductTemporary> historyList = productTemporaryDao.getHistoryByEntProductId(session,obj.getId());
        for(ProductTemporary pt:historyList){
        	if(pt.getApproveState().intValue()==ProductConstant.APPROVE_STATE_THROUGH_APPROVE.intValue()){
        		jsonMsg.setFailMsg("【"+pt.getName()+"】已审批，不能停用！");
        		return jsonMsg;
        	}
        }
            String hql = "update EntProduct set updaterId = ?,updateTime=?,status =? where id in ("+obj.getId()+")";
            Query query  = session.createQuery(hql); 
                  query.setParameter(0,obj.getUpdaterId());
                  query.setParameter(1, new Date());
                  query.setParameter(2, CUDEnum.D.toString());
                  query.executeUpdate();
                  
               //插入同步数据   
            String[] ids =obj.getId().split(","); 
            for(String id :ids){
              	EntProductSyn eps = new EntProductSyn();	
				eps.setId(id.replace("'", ""));
				eps.setSyscStatus(CUDEnum.D.toString());
				eps.setOrgId(obj.getOrgId());
				eps.setSyscTime(new Date());
				eps.setIssysc(ProductConstant.NOTSYSC);
				entProductSynDao.save(session, eps);     
            }
            return jsonMsg;
        
    }

    /**
     * <通过企业查找商品>
     * @param obj
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List<Product> findProductListbyOrgId(Session session,EntProduct obj){
        List<Product> list = null;
        Transaction tx = null;

        String hql = "from EntProduct where status !='D' and orgId in ("+obj.getOrgId()+")";
        Query query = session.createQuery(hql);
        list = query.list();
        return list;
    }
    
    
    
    public Page getList(Session session,EntProduct obj,Page page){
        String hql1 = "from EntProduct as obj where obj.status !='D' ";
        String hql2 = "select count(*) from EntProduct as obj  where obj.status !='D' ";
        if(Tools.isValid(obj)){
        	if(StringUtils.isNotBlank(obj.getName())){
                hql1=hql1 +  " and obj.name like '%"+obj.getName()+"%'";
                hql2=hql2 +  " and obj.name like '%"+obj.getName()+"%'";
            }
            if(StringUtils.isNotBlank(obj.getOrgName())){
                hql1=hql1 +  " and obj.orgName like '%"+obj.getOrgName()+"%'";
                hql2=hql2 +  " and obj.orgName like '%"+obj.getOrgName()+"%'";
            }
            if(StringUtils.isNotBlank(obj.getDesc())){
                hql1=hql1 +  " and obj.desc like '%"+obj.getDesc()+"%'";
                hql2=hql2 +  " and obj.desc like '%"+obj.getDesc()+"%'";
            }
            if(StringUtils.isNotBlank(obj.getOrgIds())){
                hql1=hql1 +  " and obj.orgId in ("+obj.getOrgIds()+")";
                hql2=hql2 +  " and obj.orgId in ("+obj.getOrgIds()+")";
            }
            if(Tools.isValid(obj.getApproveState())){
                hql1=hql1 +  " and obj.approveState ="+obj.getApproveState();
                hql2=hql2 +  " and obj.approveState ="+obj.getApproveState();
            }
        }
        hql1 += " order by createTime desc ";

        Query query = session.createQuery(hql1);
              query.setFirstResult(page.getStart()).setMaxResults(page.getLimit());
        
        page.setTotal((long) ((Long) session.createQuery(hql2)
            .uniqueResult()).intValue());
        page.setRows(query.list());
        return page;
    }
    

    public boolean decreaseProductStocks(Session session,List list){
        boolean b = false;
        Transaction tx = null;
        try
        {
            for(Iterator it = list.iterator();it.hasNext();){
            	Map map = (Map)it.next();
            	String hql = "  from AttrValue as av where av.productId = ? and av.attrName=?";
                List<AttrValue> avlist = session.createQuery(hql).setParameter(0, map.get("productId")).setParameter(1, "库存").list();
                if(!avlist.isEmpty() && avlist.size()>0){
                	AttrValue av = avlist.get(0);
                	Integer value = Integer.parseInt(av.getAttrValue())-((Integer)map.get("quantity"));
                	av.setAttrValue(value+"");
                	session.update(av);
                }
            }

            b = true ;
            return b;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return b;
        } 

    }

    /**
     * 检查当前商品状态，确定能否继续作保存操作，以防止并发问题
     * 目前检查1. 商品是否已删除. 2. 商品是否已在审批中.
     * @param conn 数据库连接
     * @param id   endProduct 主键
     */
	public void checkProductState(Connection conn, String id) throws ProcessException{
        PreparedStatement stmt = null;
        try
        {
	        String sql = "select * from p_ent_product where c_id = ? ";
	        stmt = conn.prepareStatement(sql);
	        stmt.setString(1,id);
	        ResultSet rs  = stmt.executeQuery();  
	        if(rs.next()){ 
				if(CUDEnum.D.toString().equals(rs.getString("c_status"))){
					throw new ProcessException("商品已被删除!");
				}
				if(ProductConstant.APPROVE_WAIT_APPROVE.equals(rs.getInt("i_approve_state"))){ 
					throw new ProcessException("操作失败，本次操作已终止，该记录已被其它用户占先操作!");
				}
	        }                  
        }catch (ProcessException e) {
			throw e;
		}catch (Exception e) {
			e.printStackTrace();
		}
        finally{
            this.close(stmt);
        }
	}
	public List<AttrItem> listByCategoryId(Connection conn,String categoryId,String productId) throws SQLException{
        List<AttrItem> list  = new ArrayList<AttrItem> ();
        AttrItem attr = null;
        PreparedStatement stmt = null ;
        try
        {
        String sql = "select a.c_id,a.c_name,b.c_attr_value ,a.c_groupId,a.c_desc ,b.c_product_id,a.c_type,b.i_attr_value_size,b.c_original_value " +
        		"from p_attr_item a left join p_ent_attr_value b on a.c_id = b.c_attritem_id  and b.c_product_id =?" +
        		" where a.c_status !=? and a.c_groupId in (select c_id from p_attr_group where c_category_id = ? ) ";
        stmt = conn.prepareStatement(sql);
                          stmt.setString(1,productId);
                          stmt.setString(2,CUDEnum.D.toString());
                          stmt.setString(3,categoryId);
        ResultSet rs  = stmt.executeQuery();  
        
        while(rs.next()){ 
            attr = new AttrItem();
            attr.setId(rs.getString(1));
            attr.setName(rs.getString(2));
            attr.setAttrValue(rs.getString(3));
            attr.setAttrGroup(rs.getString(4));
            attr.setDesc(rs.getString(5));
            attr.setType(rs.getString(7));
            attr.setAttrValueSize(rs.getInt(8));
            attr.setOriginalValue(rs.getString(9));
            list.add(attr);
           }                  
        }finally{
        	this.close(stmt);
        }
        return list;
    }
}
